<template>
	<div class="gk-layout-container">
		<div class="gk-layout-header">
			<!--工具栏-->
			<div class="toolbar" style="float:left;">
				<el-form :inline="true" :model="filters" :size="global.gSize">
					<el-form-item>
						<el-input v-model="filters.name" :placeholder="$t('user.name')"></el-input>
					</el-form-item>
					<el-form-item>
						<kt-button icon="fa fa-search" :label="$t('action.search')" perms="sys:user:view" type="primary"
							@click="findPage(null)" />
					</el-form-item>
					<el-form-item>
						<kt-button icon="fa fa-plus" :label="$t('action.add')" perms="sys:user:add" type="primary"
							@click="handleAdd" />
					</el-form-item>
				</el-form>
			</div>
			
		</div>
	
	
		<div class="gk-layout-main">
			<my-table :data="pageResult.content" :loading="loading"    >
				<el-table-column :label="$t('action.desc')" width="50" fixed="left"  header-align="center" align="center">
				  <template slot-scope="scope">   {{scope.$index+1}}   </template>
				</el-table-column> 
 
				<column  prop="name" :label="$t('user.name')"  />
				<column  prop="roleNames" :label="$t('user.roleNames')"     />
				<column  prop="code" :label="$t('user.code')"   />
				<column  prop="userstatus" :label="$t('user.userstatus')"   />
	  
				<el-table-column  header-align="center"  align="center"    :label="$t('action.operation')" >
					<template slot-scope="scope">
					  <kt-delete-button   perms="sys:user:delete"     @click="handleDelete(scope.$index, scope.row)" />
					  <kt-button icon="fa fa-edit"  :label="$t('action.edit')"  perms="sys:user:edit" :size="global.gSize"   @click="handleEdit(scope.$index, scope.row)" />
					</template>
				</el-table-column>
			</my-table>
		</div>
		<!--分页栏-->
		<div class="toolbar gk-layout-footer"  style="padding:10px;">
	 
		  <el-pagination layout="total, prev, pager, next, jumper"  @current-change="findPage"
						 :current-page="pageRequest.pageNum"
						 :page-size="pageRequest.pageSize"
						 :total="pageResult.totalSize"
						 style="float:right;">
		  </el-pagination>
		</div>


		<!--新增编辑界面-->
		<el-dialog :title="operation?$t('action.add'):$t('action.edit')" width="40%" :visible.sync="dialogVisible"
			:close-on-click-modal="false">
			<el-form :model="dataForm" label-width="90px" :rules="dataFormRules" ref="dataForm" :size="global.gSize"
				label-position="right">
				<el-form-item label="ID" prop="id" v-if="false">
					<el-input v-model="dataForm.id" :disabled="true" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item :label="$t('user.name')" prop="name">
					<el-input v-model.trim="dataForm.name" auto-complete="off"></el-input>
				</el-form-item>
				
				<el-form-item :label="$t('user.code')" prop="code">
					<el-input v-model="dataForm.code" auto-complete="off"></el-input>
				</el-form-item>
				
				<el-form-item :label="$t('user.roleNames')" prop="userRoles"  >
					<el-select v-model="dataForm.userRoles" multiple :placeholder="$t('action.select')"
						style="width: 100%;">
						<el-option v-for="item in roles" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button :size="global.gSize" @click.native="dialogVisible = false">{{$t('action.cancel')}}</el-button>
				<el-button :size="global.gSize" type="primary" @click.native="submitForm" :loading="editLoading">
					{{$t('action.submit')}}</el-button>
				<el-button :size="global.gSize" type="primary" @click.native="reset" :loading="resetLoading" v-if="!operation">重置密码</el-button>

			</div>
		</el-dialog>
	</div>
</template>

<script>
	import PopupTreeInput from "@/components/PopupTreeInput"
import MyTable from "@/views/Core/MyTable"
import Column from "@/views/Core/Column"
	import KtButton from "@/views/Core/KtButton"
	import KtDeleteButton from "@/views/Core/KtDeleteButton"
 
	import { format } from "@/utils/datetime"
	export default {
		components: {
			PopupTreeInput,
			MyTable,
			Column,
			KtButton,
			KtDeleteButton,
	 
		},
		data() {

		 let validatorIdNumber =  (rule, value, callback) =>{
			      const age= /^[0-9a-zA-Z]*$/
				if (!age.test(value)) {
					callback(new Error('只能为数字字母'))
				}else{
					callback()
				}
		}

			return {
				size: 'small',
				filters: {
					name: ''
				},
				columns: [],
				filterColumns: [],
				pageRequest: { pageNum: 1, pageSize: 20 },
				pageResult: {},
				loading:false,
				operation: false, // true:新增, false:编辑
				dialogVisible: false, // 新增编辑界面是否显示
				editLoading: false,
				resetLoading: false,
				param: {},
				// 新增编辑界面数据
				dataForm: {
					id: 0,
					name: '',
					passwords: '123456',
					deptId: 1,
					deptName: '',
					email: 'test@qq.com',
					mobile: '13889700023',
					userstatus: 1,
					userRoles: [],
					code: '',
					auditPassword: ''
				},
				deptData: [],
				deptTreeProps: {
					label: 'name',
					children: 'children'
				},
				roles: [],
				dataFormRules :{
					name: [{ required: true, message: this.getKey("user.userInput"), trigger: 'blur' }],
					code: [{ required: true, message: "请输入编码", trigger: 'blur' },{ validator: validatorIdNumber, trigger: 'blur' }]
				}
			}
		},
		computed: {
			
		},
		methods: {
			// 获取分页数据
			findPage: function (data) {
				if (data !== null) {
					this.filters.pageNum = data
				} else {
					this.filters.pageNum = 1
					this.pageRequest.pageNum = 1
				}
				this.filters.pageSize = this.pageRequest.pageSize
				this.$api.user.findPage(this.filters).then((res) => {
					this.pageResult = res.data
					//this.findUserRoles()				
				}).then(data != null ? data.callback : '')
			},
			// 加载用户角色信息
			findUserRoles: function () {
				this.$api.role.findAll().then((res) => {
					// 加载角色集合
					this.roles = res.data
				})
			},
			// 批量删除
			handleDelete: function (index ,row) {
				let params = [{ 'id': row.id }]
				this.$api.user.batchDelete(params).then((res) => {
					this.findPage(1);
				})
			},
			// 显示新增界面
			handleAdd: function () {
				this.dialogVisible = true
				this.operation = true
				this.dataForm = {
					id: 0,
					name: '',
					passwords: '123456',
					deptId: 1,
					deptName: '',
					email: 'test@qq.com',
					mobile: '13889700023',
					userstatus: 1,
					userRoles: [],
					code: '',
					auditPassword: ''
				}
			},
			// 显示编辑界面
			handleEdit: function (index ,row) {
				this.dialogVisible = true
			
				this.operation = false
			    row.passwords = null
				let p = Object.assign({},row)
				p.userRoles = []
				this.dataForm=p;
				this.$api.role.findUserRole({ 'userId': row.id }).then((res) => {
					// 加载角色集合
					for (let i = 0, len = res.data.length; i < len; i++) {
						p.userRoles.push(res.data[i].id);
				
					}
				})
				
			
			},
			// 提交
			submitForm: function () {
			
				this.$refs.dataForm.validate((valid) => {
					if (valid) {
						this.$confirm(this.getKey('action.isConfirm'), this.getKey('action.tips'), {}).then(() => {
							this.editLoading = true
							let params = Object.assign({}, this.dataForm)
							let userRoles = []
							for (let i = 0, len = params.userRoles.length; i < len; i++) {
								let userRole = {
									userIds: params.id,
									roleId: params.userRoles[i]
								}
								userRoles.push(userRole)
							}
							params.userRoles = userRoles
							this.$api.user.save(params).then((res) => {
								this.editLoading = false
								if (res.code == 200) {
									this.$message({ message: this.getKey('action.operateSucess'), type: 'success' })
									this.dialogVisible = false
									this.$refs['dataForm'].resetFields()
								} else {
									this.$message({ message: this.getKey('action.operateFail') + res.msg, type: 'error' })
								}
								this.findPage(null)
							})
						})
					}
				})
			},
			//重置密码
			reset: function () {
				this.$refs.dataForm.validate((valid) => {
					if (valid) {
						this.$confirm(this.getKey('action.isConfirm'), this.getKey('action.tips'), {}).then(() => {
							this.resetLoading = true
							let params = Object.assign({}, this.dataForm)
							let userRoles = []
							for (let i = 0, len = params.userRoles.length; i < len; i++) {
								let userRole = {
									userIds: params.id,
									roleId: params.userRoles[i]
								}
								userRoles.push(userRole)
							}
							params.userRoles = userRoles
							params.passwords = "123456";
							this.$api.user.save(params).then((res) => {
								this.resetLoading = false
								if (res.code == 200) {
									this.$message({ message: this.getKey('action.operateSucess'), type: 'success' })
									this.dialogVisible = false
									this.$refs['dataForm'].resetFields()
								} else {
									this.$message({ message: this.getKey('action.operateFail') + res.msg, type: 'error' })
								}
								this.findPage(null)
							})
						})
					}
				})
			},
			
			// 菜单树选中
			deptTreeCurrentChangeHandle(data, node) {
				this.dataForm.deptId = data.id
				this.dataForm.deptName = data.name
			},
			// 时间格式化
			dateFormat: function (row, column, cellValue, index) {
				return format(row[column.property])
			},
		
			
			getKey: function (arg) {
				return this.$t(arg)
			},
			// 处理表格列过滤显示
			initColumns: function () {
				this.columns = [
	
				
					
				]
				this.filterColumns = JSON.parse(JSON.stringify(this.columns));
			}
		},
		mounted() {
			//this.findDeptTree()
			this.findUserRoles()
			this.initColumns()
			this.findPage(null)
		},
		watch: {

			dialogVisible(to, from) {
				if (this.$refs['dataForm'] !== undefined) {
					this.$refs["dataForm"].resetFields();
				}
			}
		}
	}
</script>

<style scoped>

</style>